﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Attachment;
using Modules.Project.Entitys;
using Modules.Project.Repositories;
using Pipelines.Sockets.Unofficial.Arenas;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;

namespace Modules.Project
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectUpdateApplyService
    {
        private readonly ProjectUpdateApplyRepository repository;
        private readonly ProjectAttachmentService projectAttachmentService;
        private readonly ProjectGuaranteeRefundService projectGuaranteeRefundService;
        private readonly ProjectGuaranteePaymentService projectGuaranteePaymentService;
        private readonly ProjectGuaranteeAccountService projectGuaranteeAccountService;
        private readonly ProjectService projectService;
        private readonly IApplicationContext applicationContext;
        private readonly ILogger logger;

        public ProjectUpdateApplyService(ProjectUpdateApplyRepository repository, ProjectAttachmentService projectAttachmentService, ProjectGuaranteePaymentService projectGuaranteePaymentService, ProjectService projectService, IApplicationContext applicationContext, ILogger<ProjectUpdateApplyService> logger, ProjectGuaranteeRefundService projectGuaranteeRefundService, ProjectGuaranteeAccountService projectGuaranteeAccountService)
        {
            this.repository = repository;
            this.projectAttachmentService = projectAttachmentService;
            this.applicationContext = applicationContext;
            this.projectGuaranteeRefundService = projectGuaranteeRefundService;
            this.projectService = projectService;
            this.projectGuaranteePaymentService = projectGuaranteePaymentService;
            this.logger = logger;
            this.projectGuaranteeAccountService = projectGuaranteeAccountService;
        }

        public ProjectUpdateApply? GetProjectUpdateApply(int id)
        {
            return repository.Get(id);
        }

        public void Create(ProjectUpdateApply entity, List<AttachmentsForm<int>> attachments)
        {
            try
            {
                applicationContext.Transaction.Begin();
                repository.Insert(entity);

                #region 附件

                foreach (var item in attachments)
                {
                    ProjectAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item.AttachmentId,
                        ObjectId = entity.Id.ToString(),
                        Tenant = 项目附件租户.ProjectUpdateApply,
                        AttachmentType = 附件类型.中标通知书,
                        CreateTime = DateTime.Now
                    };
                    projectAttachmentService.Create(projectAttachment);
                }

                #endregion 附件

                applicationContext.Transaction.Complete();
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();
                logger.LogError(ex, $"创建修改申请失败");
                throw new BusinessException("创建修改申请失败");
            }
        }

        public void Update(ProjectUpdateApply entity, List<AttachmentsForm<int>> attachments)
        {
            try
            {
                applicationContext.Transaction.Begin();
                repository.Update(entity);

                #region 附件

                List<ProjectAttachment> projectAttachments = projectAttachmentService.GetProjectAttachmentsByObjectIdAndType(entity.Id, 附件类型.中标通知书, 项目附件租户.ProjectUpdateApply).ToList();
                projectAttachmentService.Deleted(projectAttachments.Select(i => i.Id));
                foreach (var item in attachments)
                {
                    ProjectAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item.AttachmentId,
                        ObjectId = entity.Id.ToString(),
                        Tenant = 项目附件租户.ProjectUpdateApply,
                        AttachmentType = 附件类型.中标通知书,
                        CreateTime = DateTime.Now
                    };
                    projectAttachmentService.Create(projectAttachment);
                }

                #endregion 附件

                applicationContext.Transaction.Complete();
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();
                logger.LogError(ex, $"修改修改申请失败");
                throw new BusinessException("修改修改申请失败");
            }
        }

        public void Update(ProjectUpdateApply entity)
        {
            repository.Update(entity);
        }

        public void Audit(ProjectUpdateApply entity, ProjectInfo projectInfo, List<AttachmentsForm<int>> attachments)
        {
            try
            {
                applicationContext.Transaction.Begin();
                repository.Update(entity);
                projectService.UpdateProjectInfoNoTransaction(projectInfo, new List<string>());

                #region 附件

                List<ProjectAttachment> projectAttachments = projectAttachmentService.GetProjectAttachmentsByObjectIdAndType(entity.Id, 附件类型.中标通知书, 项目附件租户.Project).ToList();
                projectAttachmentService.Deleted(projectAttachments.Select(i => i.Id));
                foreach (var item in attachments)
                {
                    ProjectAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item.AttachmentId,
                        ObjectId = projectInfo.ProjectId.ToString(),
                        Tenant = 项目附件租户.Project,
                        AttachmentType = 附件类型.中标通知书,
                        CreateTime = DateTime.Now
                    };
                    projectAttachmentService.Create(projectAttachment);
                }

                #endregion 附件

                applicationContext.Transaction.Complete();
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();
                logger.LogError(ex, $"修改完工销户申请失败");
                throw new BusinessException("修改完工销户申请失败");
            }
        }

        public bool ExistsByPrjId(int projectId)
        {
            return repository.ExistsByPrjId(projectId);
        }

        public bool ExistsByPrjIdNoAudit(int projectId)
        {
            return repository.ExistsByPrjIdNoAudit(projectId);
        }

        public ProjectUpdateApply? GetProjectUpdateApplyByProjectId(int projectId)
        {
            return repository.GetProjectUpdateApply(projectId);
        }

        /// <summary>
        /// 获取分页记录
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList<ProjectUpdateApply> GetProjectUpdateApplys(ProjectUpdateApplyQuery query, int pageIndex, int pageSize)
        {
            return repository.GetProjectUpdateApplys(query, pageIndex, pageSize);
        }

        public void Delete(int id)
        {
            repository.DeleteByEntityId(id);
        }

        public void Deleted(IEnumerable<int> ids)
        {
            foreach (int id in ids)
            {
                Delete(id);
            }
        }
    }
}